package cz.muni.fi.pv112.cranesimulator.utils.handlers.inputs;

import cz.muni.fi.pv112.cranesimulator.scene.Scene;
import java.awt.AWTException;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseEvent;

/**
 *
 * @author Michal Ďuriš
 */
public class MouseInputHandler {

    private static final float MOUSE_SENSIBILITY = 2.0f;

    private final Point mousePressedPosition = new Point();

    private boolean mouseControled = false;

    private final float[] angles = {0.0f, 0.0f};

    private MouseInputHandler() {
    }

    public static MouseInputHandler getInstance() {
        return MouseInputHandlerHolder.INSTANCE;
    }

    private static class MouseInputHandlerHolder {

        private static final MouseInputHandler INSTANCE = new MouseInputHandler();
    }

    public void processMouseEvent(MouseEvent mouseEvent, int mouseEventType) {
        if (mouseEventType == MouseEvent.MOUSE_PRESSED) {
            mousePressedPosition.setLocation(mouseEvent.getLocationOnScreen());
        } else if (mouseEventType == MouseEvent.MOUSE_DRAGGED) {
            handleMouseDragEvent(mouseEvent);
        }
    }

    private void handleMouseDragEvent(MouseEvent evt) {
        if (!mouseControled) {
            Point mouseCurrentPosition = evt.getLocationOnScreen();

            angles[Scene.X_AXIS] = (mousePressedPosition.y
                    - mouseCurrentPosition.y) / MOUSE_SENSIBILITY;
            angles[Scene.Y_AXIS] = (mouseCurrentPosition.x
                    - mousePressedPosition.x) / MOUSE_SENSIBILITY;

            centerMouse();
        }
    }

    private void centerMouse() {
        try {
            Robot mouseRobot = new Robot();
            mouseControled = true;

            mouseRobot.mouseMove(mousePressedPosition.x, mousePressedPosition.y);

            mouseControled = false;
        } catch (AWTException ex) {

        }
    }

    public float[] getResult() {
        return angles;
    }

}
